﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AnesSystem.Model;
using AnesSystem.Models;
using AnesSystem.Services;
using Common;
using MongoDB.Bson;

namespace AnesSystem.ViewModels
{
    public class AnesTemplateCtrlViewModel : BaseViewModel<AnesTemplateCtrlViewModel>
    {
        #region Variables
        private ObservableCollection<AnesRecordTemplateModel> _displayConfigAnesTemplateList;
        private List<AnesRecordTemplateModel> _templateList;
        private AnesRecordTemplateModel _selectAnesRecordTemplate;
        private List<AnesRecordTemplateModel> _tempLateList2;
        private string _searchStr;
        private AnesRecordTemplateModel _temporaryTemplate;


        #endregion


        #region Constructor
        public AnesTemplateCtrlViewModel()
        {
            _displayConfigAnesTemplateList = new ObservableCollection<AnesRecordTemplateModel>();
            _templateList = new List<AnesRecordTemplateModel>();
            SelectAnesRecordTemplate = new AnesRecordTemplateModel();

            InitData();

        }

        public void DelAnesTemplate()
        {
            try
            {
                ObjectId templateId = SelectAnesRecordTemplate.Id;
                int index = -1;
                for (int i = 0; i < TemplateList.Count; i++)
                {
                    if (templateId.Equals(TemplateList[i].Id))
                    {
                        index = i;
                        break;
                    }
                }
                if (index != -1)
                {
                    TemplateList.RemoveAt(index);
                }

                int index2 = -1;
                for (int i = 0; i < DisplayConfigAnesTemplateList.Count; i++)
                {
                    if (templateId.Equals(DisplayConfigAnesTemplateList[i].Id))
                    {
                        index2 = i;
                        break;
                    }
                }
                if (index2 != -1)
                {
                    DisplayConfigAnesTemplateList.RemoveAt(index2);
                }

                int index3 = -1;
                for (int i = 0; i < TempLateList2.Count; i++)
                {
                    if (templateId.Equals(TempLateList2[i].Id))
                    {
                        index3 = i;
                        break;
                    }
                }
                if (index3 != -1)
                {
                    TempLateList2.RemoveAt(index3);
                }
                AnesRecordTemplateModelService.Instance.DeleteById(templateId);

            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), "del AnesTemplate failed!");
            }
        }

        public void ChangeDisPlayList(string tag)
        {
            DisplayConfigAnesTemplateList.Clear();
            if (tag.Equals("ks"))
            {
                foreach (var item in TempLateList2)
                {
                    if (Constants.TEMPLATE_DEPARTMENT_ACCOUNTID.Equals(item.AccountId))
                    {
                        DisplayConfigAnesTemplateList.Add(item);
                    }
                }
            }
            if (tag.Equals("gr"))
            {
                foreach (var item in TempLateList2)
                {
                    if (!Constants.TEMPLATE_DEPARTMENT_ACCOUNTID.Equals(item.AccountId))
                    {
                        DisplayConfigAnesTemplateList.Add(item);
                    }
                }
            }

        }
        #endregion


        #region Properties
        public ObservableCollection<AnesRecordTemplateModel> DisplayConfigAnesTemplateList
        {
            get
            {
                return _displayConfigAnesTemplateList;
            }

            set
            {
                _displayConfigAnesTemplateList = value;
            }
        }

        public AnesRecordTemplateModel SelectAnesRecordTemplate
        {
            get
            {
                return _selectAnesRecordTemplate;
            }

            set
            {
                _selectAnesRecordTemplate = value;
            }
        }

        public string SearchStr
        {
            get
            {
                if (_searchStr == null)
                {
                    return "";
                }
                return _searchStr;
            }

            set
            {
                _searchStr = value;
                ChangeDisplay();
                RaisePropertyChanged("SearchStr");
            }
        }

        public List<AnesRecordTemplateModel> TemplateList
        {
            get
            {
                return _templateList;
            }

            set
            {
                _templateList = value;
            }
        }

        public List<AnesRecordTemplateModel> TempLateList2
        {
            get
            {
                return _tempLateList2;
            }

            set
            {
                _tempLateList2 = value;
            }
        }

        public AnesRecordTemplateModel TemporaryTemplate
        {
            get
            {
                return _temporaryTemplate;
            }

            set
            {
                _temporaryTemplate = value;
            }
        }

        private void ChangeDisplay()
        {
            DisplayConfigAnesTemplateList.Clear();
            foreach (var item in TemplateList)
            {
                string trueName = "";
                if (item.AccountId.Equals(Constants.TEMPLATE_DEPARTMENT_ACCOUNTID))
                {
                    trueName = "麻醉科";
                }
                else
                {
                    trueName = DataManager.Instance.GetAccountNameByID(item.AccountId);
                }
                string str = item.Name + trueName;
                if (str.IsContain(SearchStr))
                {
                    DisplayConfigAnesTemplateList.Add(item);
                }
            }
            TempLateList2 = DisplayConfigAnesTemplateList.ToList();

        }

        #endregion


        #region 依赖属性


        #endregion


        #region Event


        #endregion


        #region PrivateMethods
        private void InitData()
        {
            DisplayConfigAnesTemplateList.Clear();
            List<AnesRecordTemplateModel> list = DataManager.Instance.AnesRecordTemplateModelList.ToList();
            if (DataManager.Instance.Login.WorkID.Equals("admin"))
            {
                foreach (var item in list)
                {
                    TemplateList.Add(item);
                    DisplayConfigAnesTemplateList.Add(item);
                }
            }
            else
            {
                foreach (var item in list)
                {
                    if (item.AccountId.Equals(Constants.TEMPLATE_DEPARTMENT_ACCOUNTID) || DataManager.Instance.Login.Id.ToString().Equals(item.AccountId))
                    {
                        TemplateList.Add(item);
                        DisplayConfigAnesTemplateList.Add(item);
                    }
                }
            }
            TempLateList2 = DisplayConfigAnesTemplateList.ToList();
            ChangeDisPlayList("gr");
        }

        #endregion


        #region Public/ProtectedMethods
        public void AddTemporaryTemplate()
        {
            _temporaryTemplate = new AnesRecordTemplateModel();
            List<PatientEventsModel> eventList = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchAllEventExe();
            List<PatientDrugsModel> drugList = OperationDataPool.Instance.CurOperationData.DrugsDataCache.AllPatientDrugsList.ToList();
            AddAnesTemplateViewModel.Instance.CreatTemplate(eventList, drugList, _temporaryTemplate);
            _temporaryTemplate.Name = "Temporary";
            _temporaryTemplate.CreateTime = DateTime.Now;
        }

        public void ApplySelectTemplate(bool isDelCurData)
        {
            if (OperationDataPool.Instance.CurOperationData == null)
            {
                return;
            }
            if (SelectAnesRecordTemplate == null)
            {
                MessageBoxCommon.ShowDialog("请先选择模板！", MessageBoxCommon.OK);
                return;
            }
            if (isDelCurData)
            {
                DelExe();
                StatusModel status = PatientLink.Status;
                status.OutRoomTime = new DateTime();
                status.MazuiStartTime = new DateTime();
                status.MazuiEndTime = new DateTime();
                status.OperStartTime = new DateTime();
                status.OperEndTime = new DateTime();
                status.OperSpanTime = 0;
                status.MazuiSpanTime = 0;
                PatientLink.AnesthesiaRecord.LiquidInAndOut.JiaoTiYe = "";
                PatientLink.AnesthesiaRecord.LiquidInAndOut.JingTiYe = "";
                PatientLinkService.Instance.AddUpdate(PatientLink);
            }
            UseTemplate();
            DataManager.Instance.TableHeaderCtrl._anesProcessCtrl.ViewModel.Refresh();
        }

        private void UseTemplate()
        {
            try
            {
                List<string> exitEventCodeList = new List<string>();
                DateTime lastEventTime = new DateTime();
                List<PatientEventsModel> eventExeList = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchAllEventExe();
                foreach (var item in eventExeList)
                {
                    exitEventCodeList.Add(item.Code);
                    if (lastEventTime.Equals(new DateTime()) || lastEventTime < item.BeginTime)
                    {
                        lastEventTime = item.BeginTime;
                    }
                }
                DateTime lastDrugTime = new DateTime();
                List<PatientDrugsModel> drugList = OperationDataPool.Instance.CurOperationData.DrugsDataCache.AllPatientDrugsList.ToList();
                foreach (var item in drugList)
                {
                    if (lastDrugTime.Equals(new DateTime()) || lastDrugTime < item.BeginTime)
                    {
                        lastDrugTime = item.BeginTime;
                    }
                }
                DateTime eventTime = DateTime.Now;
                DateTime drugTime = DateTime.Now;
                if (!lastEventTime.Equals(new DateTime()))
                {
                    eventTime = lastEventTime.AddMinutes(5);
                }
                if (!lastDrugTime.Equals(new DateTime()))
                {
                    drugTime = lastDrugTime.AddMinutes(5);
                }
                if (!exitEventCodeList.Contains(Constants.EVENT_IN_ROOM))
                {
                    EventAndDrugWinViewModel.Instance.AddEvent(Constants.EVENT_IN_ROOM, eventTime);
                    eventTime = eventTime.AddMinutes(5);
                }
                List<ItemInfoModel> list = SelectAnesRecordTemplate.ItemInfoList;
                foreach (ItemInfoModel itemInfo in list)
                {
                    DrugExeInfoModel patientDrugsInfo = itemInfo.DrugExeInfo;
                    EventExeInfoModel patientEventsInfo = itemInfo.EventExeInfo;

                    if (!string.IsNullOrEmpty(patientEventsInfo.EventCode))
                    {
                        ConfigEventsModel cem = null;
                        if (DataManager.Instance.Code2events.ContainsKey(patientEventsInfo.EventCode))
                        {
                            cem = DataManager.Instance.Code2events[patientEventsInfo.EventCode];
                        }
                        else
                        {
                            cem = new ConfigEventsModel();
                            cem.Deleted = true;
                            cem.Single = true;
                            cem.EventTypeCode = "eventType_2";
                            cem.Name = patientEventsInfo.EventCode;
                            cem.Code = patientEventsInfo.EventCode;
                        }
                        if (cem == null)
                        {
                            continue;
                        }
                        EventAndDrugWinViewModel.Instance.AddEvent(cem.Code, eventTime);
                        eventTime = eventTime.AddMinutes(5);
                    }
                    else
                    {
                        if (patientDrugsInfo.Type == null) continue;
                        AddNewDrug(patientDrugsInfo, drugTime);
                        drugTime = drugTime.AddMinutes(5);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }

        }

        private void AddContinueEvent(List<PatientEventsModel> eventExes, DateTime eventTime, ConfigEventsModel cem)
        {
            foreach (var item in eventExes)
            {

            }
        }

        private void AddNewDrug(DrugExeInfoModel patientDrugsInfo, DateTime drugTime)
        {
            PatientDrugsModel pdm = new PatientDrugsModel();
            pdm.Drugs = patientDrugsInfo.Drugs;
            pdm.PatientID = PatientLink.Id.ToString();
            List<DrugSpeedModel> list = patientDrugsInfo.DrugSpeeds;
            for (int i = 0; i < list.Count; i++)
            {
                list[i].BeginTime = drugTime.AddMinutes(i * 5);
            }
            pdm.DrugSpeeds = list;
            pdm.DrugReason = patientDrugsInfo.DrugReason;
            pdm.DrugMethod = patientDrugsInfo.DrugMethod;
            pdm.Single = patientDrugsInfo.IsOnce;
            pdm.Chanel = patientDrugsInfo.Channel;
            pdm.Status = Constants.ACTION_WORK;
            pdm.Type = patientDrugsInfo.Type;
            pdm.LiquidType = patientDrugsInfo.LiquidType;
            pdm.InputTime = DateTime.Now;
            pdm.BeginTime = drugTime;
            OperationDataPool.Instance.CurOperationData.DrugsDataCache.AddAndUpdateExe(pdm);
        }

        private void DelExe()
        {
            List<PatientEventsModel> eventExeList = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchAllEventExe();
            foreach (var item in eventExeList)
            {
                if (!string.IsNullOrEmpty(item.Code) && item.Code.Equals(Constants.EVENT_IN_ROOM))
                {
                    continue;
                }
                OperationDataPool.Instance.CurOperationData.EventDataCache.DelEvent(item);

            }

            foreach (var item in OperationDataPool.Instance.CurOperationData.DrugsDataCache.AllPatientDrugsList)
            {
                OperationDataPool.Instance.CurOperationData.DrugsDataCache.DelOneExe(item);
            }
        }

        public override void Refresh()
        {
            InitData();
            //TemplateList.Clear();
            //List<AnesRecordTemplateModel> list = DataManager.Instance.AnesRecordTemplateModelList.ToList();
            //if (DataManager.Instance.Login.WorkID.Equals("admin"))
            //{
            //    foreach (var item in list)
            //    {
            //        TemplateList.Add(item);
            //    }
            //}
            //else
            //{
            //    foreach (var item in list)
            //    {
            //        if (item.AccountId.Equals(Constants.TEMPLATE_DEPARTMENT_ACCOUNTID) || DataManager.Instance.Login.Id.ToString().Equals(item.AccountId))
            //        {
            //            TemplateList.Add(item);
            //        }
            //    }
            //}
        }

        #endregion


        #region EventHandlers


        #endregion

    }
}
